package CountDownLatchTest;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenjunjie
 * @since 2018-01-17
 */
public class TPSTest {
    /**
     * 模拟请求线程数
     */
    private static final int threadNum = 1000;

    /**
     * 倒计时器
     */
    private static CountDownLatch latch = new CountDownLatch(threadNum);

    /**
     * 失败次数
     */
    private static AtomicInteger failedCount = new AtomicInteger(0);


    public static void main(String[] args) throws InterruptedException{
        // 线程池大小
        int corePoolSize = 10;
        // 线程池最大容量（最多可以存放线程的个数）
        int maxPoolSize = 10000;
        // 当前线程数大于corePoolSize, 且小于maxPoolSize时
        // this is the maximum time that excess idle threads,
        // will wait for new tasks before terminating.
        long keepActiveTime = 200;

        // 设置线程池缓存队列的排队策略为FIFO，并且指定缓存队列大小
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(corePoolSize);

        // 创建ThreadPoolExecutor线程池对象
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepActiveTime, TimeUnit.SECONDS, workQueue);

        // 创建线程
        for (int i = 0; i < threadNum; i++) {
            Thread.sleep(10);
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 业务逻辑，比如sendMsg
                        //SendResult sendResult = producer.send(message);
                        // 失败数量统计
                        //if (!SendStatus.SEND_OK) {
                        //    failedCount.incrementAndGet();
                        //}

                        latch.countDown();

                    } catch (Exception e) {
                        failedCount.incrementAndGet();
                    }
                }
            });
        }

        latch.await();

        try {
            while (executor.getActiveCount() > 0) {
                Thread.sleep(10);
            }

            // 执行TPS统计逻辑
            // (略)
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }

    }
}
